<?php
/*$Id: for_foreach.php 168 2011-03-07 03:31:10Z horseluke@126.com $*/
/*
//copy on write原理机制内探
$aa = array(
	1,
	2,
);

echo 'begin'. "\n\r";

foreach($aa as $v){
	echo "\n\r---------begin---------\n\r";
	debug_zval_dump($aa);
	$aa[] = rand(1,1);
	echo "\n\r---------after fuzhi---------\n\r";
	echo count($aa). "\n\r";
	debug_zval_dump($aa);
}
echo "\n\r---------end of fuzhi---------\n\r";
debug_zval_dump($aa);
*/

$aa = array_fill(1, 1000000, rand(1,10000000));

$processtime = 0;
$testCount = 5;


for($i=1;$i<=$testCount;$i++){
	$start = microtime();
	

/*
	foreach($aa as $x => $v){
		$d = $v;    //foreach 读
		//$aa[$x] = 'kkk';    //foreach 写
	}
*/

	for($x=1;$x<=1000000;$x++){
		$d = $aa[$x];    //for 读
		//$aa[$x] = 'kkk';    //for写
	}

	
	$end = microtime();
	$processtime += (microtime_float($end) - microtime_float($start));
}

echo $processtime/$testCount;


function microtime_float($time)
{
    list($usec, $sec) = explode(" ", $time);
    return ((float)$usec + (float)$sec);
}


/*
for 读：
H:\php4>php -f r:\xxx.php
0.443461465836
H:\php4>php -f r:\xxx.php
0.442966985703
H:\php4>php -f r:\xxx.php
0.438939762115
H:\php4>php -f r:\xxx.php
0.446066665649



foreach 读：
H:\php4>php -f r:\xxx.php
0.304050970078
H:\php4>php -f r:\xxx.php
0.305932188034
H:\php4>php -f r:\xxx.php
0.316230344772
H:\php4>php -f r:\xxx.php
0.317901134491
H:\php4>php -f r:\xxx.php
0.313235330582
H:\php4>php -f r:\xxx.php
0.304298591614
H:\php4>php -f r:\xxx.php
0.308330535889
H:\php4>php -f r:\xxx.php
0.302624797821
H:\php4>




=================================
for 读：
H:\php5>php -f "D:\PHPnow-1.5.4\htdoc_deploy\other\draftCode\for_foreach.php"
0.164170122147
H:\php5>php -f "D:\PHPnow-1.5.4\htdoc_deploy\other\draftCode\for_foreach.php"
0.157662391663
H:\php5>php -f "D:\PHPnow-1.5.4\htdoc_deploy\other\draftCode\for_foreach.php"
0.157357406616
H:\php5>php -f "D:\PHPnow-1.5.4\htdoc_deploy\other\draftCode\for_foreach.php"
0.166096830368


foreach 读：
H:\php5>php -f "D:\PHPnow-1.5.4\htdoc_deploy\other\draftCode\for_foreach.php"
0.131154584885
H:\php5>php -f "D:\PHPnow-1.5.4\htdoc_deploy\other\draftCode\for_foreach.php"
0.132294178009
H:\php5>php -f "D:\PHPnow-1.5.4\htdoc_deploy\other\draftCode\for_foreach.php"
0.139328193665
H:\php5>



======================
for 写：
H:\php5>php -f r:\xxx.php
0.257781982422
H:\php5>php -f r:\xxx.php
0.25015039444
H:\php5>php -f r:\xxx.php
0.252615785599


foreach 写（触发copy on write）：
Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate
 4 bytes) in R:\xxx.php on line 35

H:\php5>php -f r:\xxx.php

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate
 4 bytes) in R:\xxx.php on line 35

H:\php5>php -f r:\xxx.php

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate
 4 bytes) in R:\xxx.php on line 35
 */